package tools

import (
	"context"
	"encoding/json"
	"fmt"

	"mcp-db-gateway/pkg/db"
)

// DBManagerTools provides tools for managing database connections.
type DBManagerTools struct {
	dbManager *db.Manager
}

// NewDBManagerTools creates a new instance of DBManagerTools.
func NewDBManagerTools(dbManager *db.Manager) *DBManagerTools {
	return &DBManagerTools{
		dbManager: dbManager,
	}
}

// AddDatabaseParams defines the parameters for the add_database tool.
type AddDatabaseParams struct {
	Alias  string `json:"alias"`
	Type   string `json:"type"`
	DSN    string `json:"dsn"`
}

// AddDatabase adds a new database connection.
func (t *DBManagerTools) AddDatabase(ctx context.Context, paramsJSON string) (interface{}, error) {
	var params AddDatabaseParams
	if err := json.Unmarshal([]byte(paramsJSON), &params); err != nil {
		return nil, fmt.Errorf("invalid parameters: %w", err)
	}

	if params.Alias == "" || params.Type == "" || params.DSN == "" {
		return nil, fmt.Errorf("alias, type, and dsn are required")
	}

	err := t.dbManager.AddConnection(params.Alias, params.Type, params.DSN)
	if err != nil {
		return nil, err
	}

	return map[string]string{"status": "success", "message": "database added successfully"}, nil
}

// RemoveDatabaseParams defines the parameters for the remove_database tool.
type RemoveDatabaseParams struct {
	Alias string `json:"alias"`
}

// RemoveDatabase removes a database connection.
func (t *DBManagerTools) RemoveDatabase(ctx context.Context, paramsJSON string) (interface{}, error) {
	var params RemoveDatabaseParams
	if err := json.Unmarshal([]byte(paramsJSON), &params); err != nil {
		return nil, fmt.Errorf("invalid parameters: %w", err)
	}

	if params.Alias == "" {
		return nil, fmt.Errorf("alias is required")
	}

	err := t.dbManager.RemoveConnection(params.Alias)
	if err != nil {
		return nil, err
	}

	return map[string]string{"status": "success", "message": "database removed successfully"}, nil
}

// ListDatabases lists all available database aliases.
func (t *DBManagerTools) ListDatabases(ctx context.Context, paramsJSON string) (interface{}, error) {
	aliases := t.dbManager.GetDBAliases()
	return aliases, nil
}

// HealthCheck checks the connectivity of all registered databases.
func (t *DBManagerTools) HealthCheck(ctx context.Context, paramsJSON string) (interface{}, error) {
	status := t.dbManager.HealthCheck()
	return status, nil
} 